﻿using Entity;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System;
using Microsoft.VisualBasic;

namespace FastCopyWin
{
    public class ClipboardDataViewModel
    {
        private readonly ObservableCollection<ClipboardDataViewItem> clipboardDatas = new();

        internal ObservableCollection<ClipboardDataViewItem> ClipboardDataViewItemList
        {
            get
            {
               return clipboardDatas;
            }
        }

        private string DataFilePath {  get; set; }

        private int MaxRecord {  get; set; }

        public ClipboardDataViewModel(string dataFilePath, int maxRecord)
        {
            this.MaxRecord = maxRecord;
            this.DataFilePath = dataFilePath;
            if (File.Exists(dataFilePath))
            {
                string json = File.ReadAllText(dataFilePath);
                List<ClipboardData>? list = JsonConvert.DeserializeObject<List<ClipboardData>>(json);
                if (list != null)
                {
                    foreach (ClipboardData item in list)
                    {
                        clipboardDatas.Add(new(item));
                    }
                }
            }
            else 
            {
                File.WriteAllText(dataFilePath, JsonConvert.SerializeObject(new List<ClipboardData>()));
            }
            new Thread(() => { 
                while (true)
                {
                    Thread.Sleep(1000 * 60);
                    List<ClipboardData> clipboards = new();
                    lock (clipboardDatas)
                    {
                        for (int i = 0; i < clipboardDatas.Count; i++)
                        {
                            clipboards.Add(clipboardDatas[i].Data);
                        }
                    }
                    File.WriteAllText(DataFilePath, JsonConvert.SerializeObject(clipboards));
                }
            }).Start();
        }

        internal void AddUnlikeFirstData(ClipboardData data)
        {
            lock (clipboardDatas) {
                if (clipboardDatas.Count != 0 && data.Equals(clipboardDatas[0].Data)) return;
                Debug.WriteLine(data.Data);
                clipboardDatas.Insert(0, new(data));
                if (clipboardDatas.Count > Math.Max(10, MaxRecord)) 
                {
                    clipboardDatas.RemoveAt(clipboardDatas.Count - 1);
                }
            }
        }

        internal ClipboardData? GetFirstData()
        {
            if (clipboardDatas.Count > 0) return clipboardDatas[0].Data;
            return null;
        }
    }
}